/*
 * @Author: ZhangPeng irocky@email.cn
 * @Date: 2023-01-11 22:24:22
 * @Description:
 * @RoutePath:
 * Copyright (c) 2023 by ${git_name}, All Rights Reserved.
 */
import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  getUserInfo,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import type { LoginData } from '@/api/types';
import type { UserState } from './types';
import useAppStore from '../app';

const useUserStore = defineStore('user', {
  state: (): UserState => ({
    roles: [],
    permissions: [],
    user: {
      admin: false,
      avatar: '',
      email: '',
      nickName: '',
      phonenumber: '',
      remark: '',
      sex: 1,
      userName: '',
      status: 1,
    },
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    // Set user's information
    setInfo(partial: UserState) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async info() {
      const res = await getUserInfo();
      this.roles = res.roles;
      this.permissions = res.permissions;
      this.user = res.user;
      // console.log('res--->', res);
      // this.setInfo({
      //   roles: res.roles,
      //   permissions: res.permissions,
      //   user: res.user,
      // });
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
